import Vue from "vue";
import Router from "vue-router";
import store from "@/store";

Vue.use(Router);

const constantRoutes = [
  {
    path: "/404",
    component: () => import("@/views/error/404"),
    hidden: true,
  },
  {
    path: "/401",
    component: () => import("@/views/error/401"),
    hidden: true,
  },
  {
    path: "",
    component: () => import("@/layout"),
    redirect: "index",
    children: [
      { path: "index", component: () => import("@/views") },
      { path: "login", component: () => import("@/views/login") },
      { path: "register", component: () => import("@/views/register") },
      {
        path: "person",
        component: () => import("@/views/person"),
        redirect: "person/info",
        children: [
          {
            path: "info",
            component: () => import("@/views/person/info"),
          },
          {
            path: "account",
            component: () => import("@/views/person/info/account"),
          },
          {
            path: "auth",
            component: () => import("@/views/person/auth"),
          },
        ],
      },
      {
        path: "order",
        component: () => import("@/views/order"),
        meta: { requireAuth: true },
      },
      {
        path: "task",
        name: "task",
        component: () => import("@/views/task/task"),
        meta: { requireAuth: true },
      },
    ],
  },
];

const router = new Router({
  mode: "history", // 去掉url中的#
  routes: constantRoutes,
});

const originalPush = Router.prototype.push;
Router.prototype.push = function push(location, onResolve, onReject) {
  if (onResolve || onReject) return originalPush.call(this, location, onResolve, onReject);
  return originalPush.call(this, location).catch((err) => err);
};

router.beforeEach((to, from, next) => {
  if (to.meta.requireAuth) {
    if (store.state.user.token) {
      next();
    } else {
      next("/login");
    }
  } else {
    next();
  }
});

export default router;
